/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkeddata.arida.ufc.br.endpoints;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.validator.routines.UrlValidator;

/**
 *
 * @author jeovane
 */
public class LoadFileUrl {

    //String arq = "https://dl.dropbox.com/u/19076387/prefixes.txt";
    private String prefix;
    private String[] schemes = {"http", "https"};
    private UrlValidator urlValidator = new UrlValidator(schemes);
    public String[] prefixes;
    private String linha;
    private BufferedReader br;
    private File file;

    public LoadFileUrl(String prefix) {
        this.prefix = prefix;
    }
    
    public Set<String> linesArq() {
        Set<String> lines = new LinkedHashSet<String>();
        file = new File(this.prefix);

        if (file.isFile() || urlValidator.isValid(this.prefix)) {
            try {
                if (file.isFile()) {
                    FileReader fr = new FileReader(this.prefix);
                    br = new BufferedReader(fr);
                } else {
                    URL url = new URL(this.prefix);
                    URLConnection connection = url.openConnection();
                    InputStream is = url.openStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    br = new BufferedReader(isr);
                }

                while ((linha = br.readLine()) != null) {
                    lines.add(linha);
                }

                br.close();
            } catch (FileNotFoundException ex) {
                System.out.println("ERRO: " + ex);
            } catch (IOException io) {
                System.out.println("ERRO: " + io);
            }
        } else {
            System.out.println("Arquivo inválido");
        }

        return lines;
    }

}
